package com.gy.smart.life;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.google.gson.reflect.TypeToken;
import com.gy.smart.MyApplication;
import com.gy.smart.R;
import com.gy.smart.base.BaseActivity;
import com.gy.smart.base.BaseBean;
import com.gy.smart.life.bean.LifeListBean;
import com.gy.smart.life.bean.LifeTypeBean;
import com.gy.smart.life.view.LifeTitleView;
import com.gy.smart.life.view.MapMarkerView;
import com.gy.smart.util.AnimUtil;
import com.gy.smart.util.RequestResultListener;
import com.gy.smart.util.Urls;
import com.gy.smart.util.map.MapBaseDrawable;

import org.xutils.http.RequestParams;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 高岳 on 2017/1/11.
 * Describe:生活地图页
 */
public class LifeMapActivity extends BaseActivity implements LifeTitleView.LifeTitleSelect,AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener,
        AMap.OnMarkerClickListener {

    private LifeTitleView titleView;
    private MapView mapView;
    private LinearLayout llDetail;
    private TextView tvName,tvPhone,tvAddress;
    private List<String> strTitles;
    private List<LifeTypeBean> lifeCategoryList;
    private AMap aMap;
    private LatLng center;//地图中心点
    private MapBaseDrawable mMapBaseDrawable;
    private List<LifeListBean> mDatas;
    private AMapLocation aMapLocation;//定位位置信息
    private int clickPosition,selectTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewRes(R.layout.activity_life_map);
        setTitleMsg("生活服务地图");
        _baseRight_text.setText("列表");
        titleView = (LifeTitleView) findViewById(R.id.activity_life_map_title);
        mapView = (MapView) findViewById(R.id.activity_life_mapview);
        llDetail = (LinearLayout) findViewById(R.id.activity_life_map_ll_detail);
        tvName = (TextView) findViewById(R.id.activity_life_map_tv_name);
        tvPhone = (TextView) findViewById(R.id.activity_life_map_tv_phone);
        tvAddress = (TextView) findViewById(R.id.activity_life_map_tv_address);

        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        initDatas();
        setListeners();
        fillDatas();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    private void initDatas(){
        lifeCategoryList = (List<LifeTypeBean>) getIntent().getSerializableExtra("titles");
        strTitles = new ArrayList<>();
        if(lifeCategoryList != null){
            for(LifeTypeBean typeBean : lifeCategoryList){
                strTitles.add(typeBean.lc_name);
            }
        }
        center = new LatLng(MyApplication.aMapLocation.getLatitude(), MyApplication.aMapLocation.getLongitude());
        mDatas = new ArrayList<>();
    }

    private void setListeners() {
        super.setListener();
        titleView.setListener(this);
        titleView.setTitles(strTitles);
        llDetail.setOnClickListener(this);
        BitmapDescriptor centerBit = BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.mipmap.ic_my_loc));
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);//设置地图缩放按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置地图zoom级别
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(center));
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
//        aMap.addMarker(new MarkerOptions().position(center).icon(centerBit).draggable(true));

        mMapBaseDrawable = new MapMarkerView(this);

//        for (int i = 0; i < mDatas.size(); i++) {
//            aMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(mDatas.get(i).y),Double.valueOf(mDatas.get(i).x)))
//                    .icon(BitmapDescriptorFactory.fromBitmap(mMapBaseDrawable.createMarker(mDatas.get(i)))).draggable(true).title(i+""));
//        }
    }

    private void fillDatas() {
        super.fillData();
        if(lifeCategoryList == null){
            requestType();
        }
        if(MyApplication.aMapLocation != null){
            this.aMapLocation = MyApplication.aMapLocation;
            requestData("-1");
        }
    }

    @Override
    public void doClick(View v) {
        super.doClick(v);
        Intent intent;
        switch (v.getId()){
            case R.id._right:
                intent = new Intent(this,LifeListActivity.class);
                intent.putExtra("titles", (Serializable) lifeCategoryList);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                break;
            case R.id.activity_life_map_ll_detail:
                intent = new Intent(this,LifeDetailActivity.class);
                intent.putExtra("life_id",mDatas.get(clickPosition).life_id);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                break;
        }
    }

    @Override
    public void lifeTitleSelect(int position) {
        llDetail.setVisibility(View.GONE);
        if(selectTitle != position){
            selectTitle = position;
            requestData(lifeCategoryList.get(position - 1).lc_id);
        }
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        llDetail.setVisibility(View.VISIBLE);
        clickPosition = Integer.valueOf(marker.getTitle());
        tvName.setText(mDatas.get(Integer.valueOf(marker.getTitle())).title+"");
        tvPhone.setText("联系电话："+mDatas.get(Integer.valueOf(marker.getTitle())).tel+"");
        tvAddress.setText("地址："+mDatas.get(Integer.valueOf(marker.getTitle())).address+"");
        int loc = Integer.valueOf(marker.getTitle());
        for (LifeListBean bean : mDatas){
            bean.isSelect = 0;
        }
        mDatas.get(loc).isSelect = 1;
        aMap.clear();
        for (int i = 0; i < mDatas.size(); i++) {
            aMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(mDatas.get(i).latitude),
                    Double.valueOf(mDatas.get(i).longitude)))
                    .icon(BitmapDescriptorFactory.fromBitmap(mMapBaseDrawable.createMarker(mDatas.get(i))))
                    .draggable(true).title(i+""));
        }
        return false;
    }

    /** 请求分类*/
    private void requestType(){
        showLoadDialog();
        RequestParams params = new RequestParams(Urls.url_life_type);
        postRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                if(result.status == 1){
                    Type type = new TypeToken<List<LifeTypeBean>>(){}.getType();
                    lifeCategoryList = gson.fromJson(result.data,type);
                    if(lifeCategoryList != null){
                        strTitles.clear();
                        for(LifeTypeBean typeBean : lifeCategoryList){
                            strTitles.add(typeBean.lc_name);
                        }
                        titleView.setTitles(strTitles);
                    }
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
        });
    }

    private void requestData(String id){
        showLoadDialog();
        RequestParams params = new RequestParams(Urls.url_life_list);
        if("-1".equals(id)){
            params.addParameter("lc_id","");
        } else {
            params.addParameter("lc_id",id+"");
        }
        params.addParameter("longitude",aMapLocation.getLongitude()+"");
        params.addParameter("latitude",aMapLocation.getLatitude()+"");
        params.addParameter("page","1");
        params.addParameter("pagenum","10000");
        postRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                aMap.clear();
                if(result.status == 1){
                    Type type = new TypeToken<List<LifeListBean>>(){}.getType();
                    mDatas = gson.fromJson(result.data,type);
                    for (int i = 0; i < mDatas.size(); i++) {
                        aMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(mDatas.get(i).latitude),
                                Double.valueOf(mDatas.get(i).longitude)))
                                .icon(BitmapDescriptorFactory.fromBitmap(mMapBaseDrawable.createMarker(mDatas.get(i))))
                                .draggable(true).title(i+""));
                    }
                    if(mDatas.size() > 0){
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(Double.valueOf(mDatas.get(0).latitude),
                                Double.valueOf(mDatas.get(0).longitude))));
                    }
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
        });
    }
}
